package com.lab.app;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.app.MainApplication;
import com.cuitrip.app.util.FontManager;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.login.proxy.LoginProxy;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.business.user.proxy.UserInfoProxy;
import com.cuitrip.push.PushService;
import com.cuitrip.service.R;
import com.cuitrip.util.DialogUtil;
import com.facebook.appevents.AppEventsLogger;
import com.lab.component.common.BaseDialogFragment;
import com.lab.component.common.IUIController;
import com.lab.jumper.ActivityManager;
import com.lab.jumper.FragmentJumper;
import com.lab.logtrack.AppLog;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.AnalyticsHelper;
import com.pingplusplus.android.PaymentActivity;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;

import java.util.HashSet;
import java.util.Set;

import cn.pedant.SweetAlert.SweetAlertDialog;
import rx.Subscriber;

public class BaseActivity extends AppCompatActivity implements IUIController {

    public static final int REQUEST_CODE_PAYMENT = 1001;

    public static final String PAY_CHANEL_ALIPAY = "alipay";
    public static final String PAY_CHANEL_WXPAY = "wx";
    private static volatile boolean sAnalyticse = false;
    // 宿主Dialog集合
    protected Set<BaseDialogFragment> mDialogFragmentSet = new HashSet<BaseDialogFragment>();
    protected Set<Subscriber> subscriberSet = new HashSet<>();
    InputMethodManager manager;
    private SweetAlertDialog mLoadingDialog;
    private Dialog mNoCancelDialog;

    protected boolean appTheme(){
        return true;
    }

    private void applayTheme(){
        if (appTheme()){
            if (UserInfoProxy.getInstance().isTraveller()) {
                setTheme(R.style.ct_traveller_theme);
            } else {
                setTheme(R.style.ct_finder_theme);
            }
        }
    }

    /**
     * **************************************************
     * System Method
     * **************************************************
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.ct_black));
        }
        applayTheme();
        super.onCreate(savedInstanceState);
        FontManager.changeActivityFonts(this);
        manager  = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        ActivityManager.getInstance().addActivity(this);
        if (!sAnalyticse) {
            AnalyticsHelper.updateOnlineConfig(this.getApplicationContext());
            AnalyticsHelper.enableEncrypt(true);
            AnalyticsHelper.setDebugMode(MainApplication.IS_DEV);
            PushAgent mPushAgent = PushAgent.getInstance(this.getApplicationContext());
            mPushAgent.enable(new IUmengRegisterCallback() {

                @Override
                public void onRegistered(String registrationId) {
                    //onRegistered方法的参数registrationId即是device_token
                    CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();

                    UserBusiness.updateDeviceToken(new ApiProxy(new IProxyCallback() {
                        @Override
                        public boolean onProxyResult(ProxyResult<?> result) {
                            return true;
                        }
                    }), userInfo);
                }
            });
            mPushAgent.setPushIntentServiceClass(PushService.class);
            sAnalyticse = true;
        }
        PushAgent.getInstance(this).onAppStart();
    }

    protected void onCreate(Bundle savedInstanceState, int layoutResId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.ct_black));
        }
        applayTheme();
        super.onCreate(savedInstanceState);
        manager  = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        }
        ActivityManager.getInstance().addActivity(this);
        if (!sAnalyticse) {
            AnalyticsHelper.updateOnlineConfig(this.getApplicationContext());
            AnalyticsHelper.enableEncrypt(true);
            AnalyticsHelper.setDebugMode(MainApplication.IS_DEV);
            PushAgent mPushAgent = PushAgent.getInstance(this.getApplicationContext());
            mPushAgent.enable();
            mPushAgent.setPushIntentServiceClass(PushService.class);
            sAnalyticse = true;
        }
        PushAgent.getInstance(this).onAppStart();
        FontManager.changeActivityFonts(this);
        setContentView(layoutResId);
    }

    protected void onCreate(Bundle savedInstanceState, View rootView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.ct_black));
        }
        applayTheme();
        super.onCreate(savedInstanceState);
        manager  = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        }
        ActivityManager.getInstance().addActivity(this);
        if (!sAnalyticse) {
            AnalyticsHelper.updateOnlineConfig(this.getApplicationContext());
            AnalyticsHelper.enableEncrypt(true);
            AnalyticsHelper.setDebugMode(MainApplication.IS_DEV);
            PushAgent mPushAgent = PushAgent.getInstance(this.getApplicationContext());
            mPushAgent.enable();
            mPushAgent.setPushIntentServiceClass(PushService.class);
            sAnalyticse = true;
        }
        PushAgent.getInstance(this).onAppStart();
        FontManager.changeActivityFonts(this);
        setContentView(rootView);
    }


    public void showLoading() {
        showLoading(true);
    }

    protected void showLoading(boolean cancel) {
        if (mLoadingDialog == null) {
            mLoadingDialog = DialogUtil.createSweetLoadingProgressDialog(this, cancel);
        }
        mLoadingDialog.show();
    }

    public void hideLoading() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    protected void showNoCancelDialog() {
        if (mNoCancelDialog == null) {
            mNoCancelDialog = DialogUtil.createSweetLoadingProgressDialog(this, false);
        }
        mNoCancelDialog.show();
    }

    protected void hideNoCancelDialog() {
        if (mNoCancelDialog != null) {
            mNoCancelDialog.dismiss();
        }
    }


    public void pay(String data) {
        Intent intent = new Intent();
        String packageName = getPackageName();
        ComponentName componentName = new ComponentName(packageName, packageName + ".wxapi.WXPayEntryActivity");
        intent.setComponent(componentName);
        intent.putExtra(PaymentActivity.EXTRA_CHARGE, data);
        startActivityForResult(intent, REQUEST_CODE_PAYMENT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == LoginProxy.REQUEST_LOGIN) {
            if (resultCode == RESULT_OK && LoginInstance.isLogin()) {
                onLoginSuccess();
                return;
            } else {
                onLoginFailed();
            }
        }
        if (requestCode == REQUEST_CODE_PAYMENT) {
            if (resultCode == RESULT_OK) {
                String result = data.getExtras().getString("pay_result");
            /* 处理返回值
             * "success" - payment succeed
             * "fail"    - payment failed
             * "cancel"  - user canceld
             * "invalid" - payment plugin not installed
             *
             * 如果是银联渠道返回 invalid，调用 UPPayAssistEx.installUPPayPlugin(this); 安装银联安全支付控件。
             */
                if (result != null) {
                    switch (result) {
                        case "success":
                            onPaySuccess();
                            break;
                        case "fail":
                            onPayFailed(getString(R.string.pay_operation_pay_feedback_fail));
                            break;
                        case "cancel":
                            onPayCancel();
                            break;
                        case "invalid":
//                            onPayFailed(getString(R.string.ct_pay_invalid));
                            break;
                        default:
                            String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
                            onPayFailed(errorMsg);
                            break;
                    }
                }
//                Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
            } else if (resultCode == RESULT_CANCELED) {
//                Toast.makeText(this, "User canceled", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    protected void onPaySuccess() {

    }

    protected void onPayFailed(String msg) {

    }

    protected void onPayCancel(){

    }

    protected void onLoginSuccess() {

    }

    protected void onLoginFailed() {

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        setStartAnimation();
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        setStartAnimation();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setFinishAnimation();
    }

    @Override
    public void finish() {
        super.finish();
        setFinishAnimation();
    }

    protected void setStartAnimation() {
        overridePendingTransition(R.anim.ct_slide_in_right, R.anim.ct_slide_out_left);
    }

    protected void setFinishAnimation() {
        overridePendingTransition(R.anim.ct_slide_in_left, R.anim.ct_slide_out_right);
    }

    protected void onResume() {
        super.onResume();
        AnalyticsHelper.onResume(this);
        AppEventsLogger.activateApp(this);
    }

    protected void onPause() {
        super.onPause();
        AnalyticsHelper.onPause(this);
        AppEventsLogger.deactivateApp(this);
    }

    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.getInstance().removeActivity(this);
        if (mNoCancelDialog != null && mNoCancelDialog.isShowing()) {
            mNoCancelDialog.dismiss();
        }
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        releaseSubscribers();
    }

    private void releaseSubscribers(){
        for (Subscriber subscriber : subscriberSet){
            if (!subscriber.isUnsubscribed()){
                subscriber.unsubscribe();
            }
        }
    }

    protected void onNetwokError(int nameRes, int drawableRes, int layout) {

    }

    protected void onEmpyData(int nameRes, int drawableRes, int layout) {

    }

    protected void setViewImage(int id, int drawableId) {
        ImageView tempImageView = (ImageView) findViewById(id);
        if (tempImageView != null) {
            tempImageView.setImageResource(drawableId);
        }
    }

    public void setViewText(int id, CharSequence text) {
        TextView v = (TextView) findViewById(id);
        if (v != null) {
            v.setText(text);
        }
    }

    public void removeView(int id) {
        View view = findViewById(id);
        if (view != null) {
            view.setVisibility(View.GONE);
        }
    }

    public void showView(int id) {
        View view = findViewById(id);
        if (view != null) {
            view.setVisibility(View.VISIBLE);
        }
    }

    protected void hideView(int id) {
        View view = findViewById(id);
        if (view != null) {
            view.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public final FragmentManager getOptimizedFragmentManager() {
        return this.getSupportFragmentManager();
    }

    @Override
    public void showDialogFragment(BaseDialogFragment dialog) {
        if (null != dialog && !isFinishing()) {
            try {
                dialog.show(getOptimizedFragmentManager(), null);
                mDialogFragmentSet.add(dialog);
            } catch (Exception e) {
                AppLog.w(e.getMessage());
            }
        }
    }

    @Override
    public void hideDialogFragment(BaseDialogFragment dialog) {
        if (null != dialog) {
            try {
                dialog.dismissAllowingStateLoss();
                mDialogFragmentSet.remove(dialog);
            } catch (Exception e) {
                AppLog.w(e.getMessage());
            }
        }
    }

    public void setWithIconFont(TextView... textViews) {
        for (TextView textView : textViews) {
            if (textView != null) {
                textView.setTypeface(MainApplication.getInstance().getIconFont());
            }
        }

    }




    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null && manager != null) {
                try{
                    manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }catch (Exception e){
                    //防止出键盘错误
                }
            }
        }
        return super.onTouchEvent(event);
    }

    public Subscriber addSubscriber(Subscriber subscriber){
        subscriberSet.add(subscriber);
        return subscriber;
    }


    public final FragmentManager getCustomSelfFragmentManager() {
        return getSupportFragmentManager();
    }

    public void openFragment(Fragment fragment, int containId, String tag) {
        FragmentJumper.addFragment(getCustomSelfFragmentManager(), containId, fragment, tag, false);
    }

    public void openFragment(Fragment fragment, int containId, String tag, boolean addBackStatck) {
        FragmentJumper.addFragment(getCustomSelfFragmentManager(), containId, fragment, tag, addBackStatck);
    }
}
